﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Office.Interop.Excel;
using Microsoft.Win32;
using System.Windows;
using T_BPI.Classes.Base;
using System.Diagnostics;
using System.Windows.Controls;


namespace T_BPI.Classes.Model
{
    public class ExcelPort
    {
        public string[] columnNames;
        public double[,] inputData;
        public ProgressBar progressBar = null;
        public Int32 row , col ;

        private Microsoft.Office.Interop.Excel.Application ObjExcel;
        private Workbook ObjWorkBook;
        private Worksheet ObjWorkSheet;

        public ExcelPort(ProgressBar progresBar_)
        {
            this.progressBar = progresBar_;
        }

        public void ReadFile()
        {
            //Диалоговое окно выбора файла с фильтром
            OpenFileDialog openDialog = new OpenFileDialog();
            openDialog.Filter = "Файл Excel|*.XLSX;*.XLS";
            bool? fileChoosen = openDialog.ShowDialog();
            if (fileChoosen == null || fileChoosen == false)
                return;
            try
            {
                //Приложение самого Excel
                ObjExcel = new Microsoft.Office.Interop.Excel.Application();
                //Книга.
                ObjWorkBook = ObjExcel.Workbooks.Open(openDialog.FileName);
                //Таблица.
                ObjWorkSheet = ObjExcel.ActiveSheet as Worksheet;
                //Ячейка
                Range rg = null;
                row = col = 1;
                
                while (ObjWorkSheet.get_Range("a" + row).Value != null)
                    row++;

                while (ObjWorkSheet.get_Range(numberToExcelChar(col) + "1").Value != null)
                    col++;
                row--;
                col--;
                columnNames = new string[col];
                inputData = new double[row, col];
                progressBar.Dispatcher.Invoke(() =>
                {
                    progressBar.Maximum = col * row;
                    progressBar.Minimum = 0;
                    progressBar.Value = 0;
                });


                char currentCol = (char)65;
                rg = ObjWorkSheet.get_Range(currentCol + "1", numberToExcelChar(col) + "1");
                int i = 0;
                foreach (Range item in rg)
                {
                    try
                    {
                        string value = item.Value.ToString().Trim();
                        columnNames[i] = value;
                    }
                    catch
                    {
                        columnNames[i] = "Error reading - " + item.XPath.ToString();
                    }
                    progressBar.Dispatcher.Invoke(() =>
                    {
                        progressBar.Value += 1;
                    });
                    i++;
                }

                for (int j = 0; j < row - 1; j++)
                {
                    int rowNumber = 2 + j;
                    rg = ObjWorkSheet.get_Range("A" + rowNumber, numberToExcelChar(col) + rowNumber);
                    i = 0;
                    foreach (Range item in rg)
                    {
                        try
                        {
                            string value = item.Value.ToString().Trim();
                            inputData[j, i] = Double.Parse(value);
                        }
                        catch
                        {
                            inputData[j, i] = 0.0;
                            Utils.Log("Error reading data {0}", item.XPath.ToString());
                        }
                        progressBar.Dispatcher.Invoke(() =>
                        {
                            progressBar.Value += 1;
                        });
                        i++;
                    }
                }
                MessageBox.Show("Данные загружены", "Считывания excel файла");
            }
            catch (Exception ex) { MessageBox.Show("Ошибка: " + ex.Message, "Ошибка при считывании excel файла"); }

        }

        private string numberToExcelChar(Int32 num)
        {
            if (num <= 26)
            {
                //Utils.Log("{0}", char.ConvertFromUtf32(65 + num));
                return char.ConvertFromUtf32(64 + num);
            }
            else
            {
                //Utils.Log("{0}{1} - {2} ", char.ConvertFromUtf32(64 + num / 27), char.ConvertFromUtf32(65 + (num - 1) % 26), num);
                return char.ConvertFromUtf32(64 + num / 27) + char.ConvertFromUtf32(65 + (num - 1) % 26);
            }
        }

    }
}
